
import {Controller} from "../mvcFrame/Controller";
import {CCComponent} from "../base/CCComponent";

const {ccclass, property} = cc._decorator;
/*
*ClassName:ObjectPool
*Description:TODO
*Date:2019/10/26 14:32
*/
@ccclass
export default class ObjectPool<T> extends CCComponent {

    public pool: any[];
    public objPrefab: cc.Prefab;
    private parent: cc.Node;
    private cacheParent: cc.Node;


    /***创建对象池*/
    public InitPool(prefab: cc.Prefab, parent: cc.Node) {
        this.pool = [];
        this.objPrefab = prefab;
        this.parent = parent;

        this.cacheParent = new cc.Node();
        this.cacheParent.setParent(this.parent);
    }

    public GetElement<T extends Controller>(forceCreate: boolean = false): T {
        if (forceCreate) {
            for (let i = this.pool.length - 1; i >= 0; i--) {
                let element = this.pool[i];
                if(!element){
                    continue;
                }
                if(!element.node){
                    continue;
                }
                if(!element.node.activeInHierarchy){
                    element.node.active = true;
                    element.node.setParent(this.parent);
                    return element;
                }
            }
        } else {
            let inst: T = null;
            try {
                let obj = cc.instantiate(this.objPrefab);
                obj.setParent(this.parent);
                inst = <T>obj.getComponent(Controller);

            } catch (e) {
                console.error("Pool Exception", e.message, "/Pool Parent Name = ", parent.name);
            }
            this.pool.push(inst);

            return inst;
        }
    }
}